package cn.disicn.util;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Shape;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpSession;
import net.iharder.Base64;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import cn.disicn.common.Const;

/**
 * 
 * @Description:Java生成二维码和图片验证码
 * @author: Luyao
 * @date: 2017年9月22日 上午9:58:25
 */
public class ImageUtil {

	// 内容编码
	private static final String charSet = "UTF-8";
	// 图片格式
	private static final String formatName = "png";
	// 二维码尺寸
	private static final Integer qrcodeSize = 300;
	// LOGO宽度
	private static final Integer WIDTH = 60;
	// LOGO高度
	private static final Integer HEIGHT = 60;

	/**
	 * 创建、合成二维码图片
	 * 
	 * @param content
	 * @param imgPath
	 * @param needCompress
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	private static BufferedImage createImage(String content, String imgPath,
			boolean needCompress) {
		@SuppressWarnings("rawtypes")
		Hashtable hints = new Hashtable();
		hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
		hints.put(EncodeHintType.CHARACTER_SET, charSet);
		hints.put(EncodeHintType.MARGIN, 1);
		try {
			BitMatrix bitMatrix = new MultiFormatWriter().encode(content,
					BarcodeFormat.QR_CODE, qrcodeSize, qrcodeSize, hints);
			int width = bitMatrix.getWidth();
			int height = bitMatrix.getHeight();
			BufferedImage image = new BufferedImage(width, height,
					BufferedImage.TYPE_INT_RGB);
			for (int x = 0; x < width; x++) {
				for (int y = 0; y < height; y++) {
					image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000
							: 0xFFFFFFFF);
				}
			}
			if (imgPath == null || "".equals(imgPath)) {
				return image;
			}
			// 插入图片
			insertImage(image, imgPath, needCompress);
			return image;
		} catch (WriterException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 插入logo
	 * 
	 * @param source
	 * @param imgPath
	 * @param needCompress
	 * @throws Exception
	 */
	private static void insertImage(BufferedImage source, String imgPath,
			boolean needCompress) throws Exception {
		File file = new File(imgPath);
		if (!file.exists()) {
			System.err.println("" + imgPath + "   该文件不存在！");
			return;
		}
		Image src = ImageIO.read(new File(imgPath));
		int width = src.getWidth(null);
		int height = src.getHeight(null);
		if (needCompress) { // 压缩LOGO
			if (width > WIDTH) {
				width = WIDTH;
			}
			if (height > HEIGHT) {
				height = HEIGHT;
			}
			Image image = src.getScaledInstance(width, height,
					Image.SCALE_SMOOTH);
			BufferedImage tag = new BufferedImage(width, height,
					BufferedImage.TYPE_INT_RGB);
			Graphics g = tag.getGraphics();
			g.drawImage(image, 0, 0, null); // 绘制缩小后的图
			g.dispose();
			src = image;
		}
		// 插入LOGO
		Graphics2D graph = source.createGraphics();
		int x = (qrcodeSize - width) / 2;
		int y = (qrcodeSize - height) / 2;
		graph.drawImage(src, x, y, width, height, null);
		Shape shape = new RoundRectangle2D.Float(x, y, width, width, 6, 6);
		graph.setStroke(new BasicStroke(3f));
		graph.draw(shape);
		graph.dispose();
	}

	/**
	 * 生成二维码图片二进制数据返回到前端显示
	 * 
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	public static String qrCode(String content, String payType,
			HttpSession session) {
		String logoPath = "";
		if (payType.equals(Const.PayTypeEnum.ALIPAY.getCode() + "")) {
			logoPath = session.getServletContext().getRealPath(
					"/static/img/alipaylogo.jpg");
		} else if (payType.equals(Const.PayTypeEnum.WECHATPAY.getCode() + "")) {
			logoPath = session.getServletContext().getRealPath(
					"/static/img/wechatpaylogo.jpg");
		}
		BufferedImage image = createImage(content, logoPath, true);
		String binary = null;
		try {
			// 1、读取文件转换为字节数组
			ByteArrayOutputStream output = new ByteArrayOutputStream();
			ImageIO.write(image, formatName, output);
			byte[] bytes = output.toByteArray();
			// 2、将字节数组转为二进制
			binary = Base64.encodeBytes(bytes).trim();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return binary;
	}

	/**
	 * 以下为验证码生成相关
	 */
	private static final Font FONT = new Font("Times New Roman", Font.PLAIN, 17);

	/**
	 * 得到随机颜色
	 * 
	 * @param fc
	 * @param bc
	 * @return
	 */
	private static Color getRandColor(int fc, int bc) {
		Random random = new Random();
		if (fc > 255)
			fc = 255;
		if (bc > 255)
			bc = 255;
		int r = fc + random.nextInt(bc - fc);
		int g = fc + random.nextInt(bc - fc);
		int b = fc + random.nextInt(bc - fc);
		return new Color(r, g, b);
	}

	/**
	 * 
	 * @Description:返回验证码和图片二进制数据
	 * @date: 2017年9月22日 上午11:14:55
	 * @return
	 * @throws IOException
	 */
	public static Map<String, String> getGraphics() {
		int width = 100, height = 20;
		BufferedImage image = new BufferedImage(width, height,
				BufferedImage.TYPE_INT_BGR);
		Graphics g = image.getGraphics();
		Random random = new Random();
		g.setColor(getRandColor(200, 250));
		g.fillRect(1, 1, width - 1, height - 1);
		g.setColor(new Color(102, 102, 102));
		g.drawRect(0, 0, width - 1, height - 1);
		g.setFont(FONT);
		g.setColor(getRandColor(160, 200));
		// 画随机线
		for (int i = 0; i < 155; i++) {
			int x = random.nextInt(width - 1);
			int y = random.nextInt(height - 1);
			int xl = random.nextInt(6) + 1;
			int yl = random.nextInt(12) + 1;
			g.drawLine(x, y, x + xl, y + yl);
		}
		// 从另一方向画随机线
		for (int i = 0; i < 70; i++) {
			int x = random.nextInt(width - 1);
			int y = random.nextInt(height - 1);
			int xl = random.nextInt(12) + 1;
			int yl = random.nextInt(6) + 1;
			g.drawLine(x, y, x - xl, y - yl);
		}
		// 生成随机数,并将随机数字转换为字母
		String sRand = "";
		for (int i = 0; i < 6; i++) {
			int itmp = random.nextInt(26) + 65;
			char ctmp = (char) itmp;
			sRand += String.valueOf(ctmp);
			g.setColor(new Color(20 + random.nextInt(110), 20 + random
					.nextInt(110), 20 + random.nextInt(110)));
			g.drawString(String.valueOf(ctmp), 15 * i + 10, 16);
		}
		g.dispose();
		String binary = null;
		try {
			// 1、读取文件转换为字节数组
			ByteArrayOutputStream output = new ByteArrayOutputStream();
			ImageIO.write(image, formatName, output);
			byte[] bytes = output.toByteArray();
			// 2、将字节数组转为二进制
			binary = Base64.encodeBytes(bytes).trim();
		} catch (Exception e) {
			e.printStackTrace();
		}
		Map<String, String> map = new HashMap<String, String>();
		map.put("rand", sRand);
		map.put("image", binary);
		return map;
	}
}